// ** React Imports
import { ReactNode, useState } from "react";

// ** MUI Components
import Button from "@mui/material/Button";
import Divider from "@mui/material/Divider";
import Checkbox from "@mui/material/Checkbox";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import Box from "@mui/material/Box";
import { styled, useTheme } from "@mui/material/styles";
import InputAdornment from "@mui/material/InputAdornment";
import MuiFormControlLabel, {
  FormControlLabelProps,
} from "@mui/material/FormControlLabel";

// ** Custom Component Import
import CustomTextField from "../../@core/components/mui/text-field";

// ** Icon Imports
import Icon from "../../@core/components/icon";

// ** Third Party Imports
import * as yup from "yup";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";

// ** Layout Import
import BlankLayout from "../../@core/layouts/BlankLayout";

// ** Demo Imports
import { JWTAtom } from "../../hooks/useLogin.ts";
import { encrypt } from "../../utils/encrypt.ts";
import { useNavigate } from "react-router-dom";

import Bg from "../../assets/images/login-background.png";
import Grid from "@mui/material/Grid";
import { Message } from "@arco-design/web-react";
import { APIError } from "../../api";
import { useSetAtom } from "jotai/index";
import { useAPI } from "../../hooks/useAPI.ts";

const FormControlLabel = styled(MuiFormControlLabel)<FormControlLabelProps>(
  ({ theme }) => ({
    "& .MuiFormControlLabel-label": {
      color: theme.palette.text.secondary,
    },
  }),
);
interface LoginFormInputs {
  username: string;
  password: string;
}
const schema = yup.object().shape({
  username: yup.string().required(),
  password: yup.string().min(5).required(),
});

const LoginPage = () => {
  const [rememberMe, setRememberMe] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState<boolean>(false);

  // ** Hooks
  const api = useAPI();
  const setJWT = useSetAtom(JWTAtom);
  const navigate = useNavigate();
  const theme = useTheme();

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormInputs>({
    mode: "onBlur",
    resolver: yupResolver(schema),
  });

  const onSubmit = (data: { username: any; password: any }) => {
    let { username, password } = data;
    password = encrypt(password);
    return api
      .login({ username, password })
      .then((res) => {
        Message.success("登录成功");
        setJWT(res.data.data);
        navigate("/homepage/index");
      })
      .catch((error) => {
        if (error instanceof APIError) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      });
  };

  // @ts-ignore
  return (
    <Box>
      <Grid
        container
        spacing={3}
        sx={{
          backgroundImage: `url(${Bg})`,
          backgroundSize: "cover",
          justifyContent: "right",
          alignItems: "center",
          height: "100.9vh",
        }}
      >
        <Grid
          item
          xs={3}
          sx={{
            p: [6, 12],
            height: "100%",
            display: "fixed",
            alignItems: "center",
            justifyContent: "center",
            background: "white",
          }}
        >
          <Box sx={{ width: "100%", maxWidth: 350 }}>
            <Box sx={{ my: 12 }}>
              <Typography variant="h3" sx={{ mb: 1.5 }}>
                睿首智慧康养系统
              </Typography>
              <Typography sx={{ color: "text.secondary" }}>请登录</Typography>
            </Box>
            <form
              noValidate
              autoComplete="off"
              onSubmit={handleSubmit(onSubmit)}
            >
              <Box sx={{ mb: 4 }}>
                <Controller
                  name="username"
                  control={control}
                  rules={{ required: true }}
                  render={({ field: { value, onChange, onBlur } }) => (
                    <CustomTextField
                      fullWidth
                      autoFocus
                      variant="outlined"
                      label="用户名"
                      value={value}
                      onBlur={onBlur}
                      onChange={onChange}
                      error={Boolean(errors.username)}
                      {...(errors.username && {
                        helperText: errors.username.message,
                      })}
                    />
                  )}
                />
              </Box>
              <Box sx={{ mb: 1.5 }}>
                <Controller
                  name="password"
                  control={control}
                  rules={{ required: true }}
                  render={({ field: { value, onChange, onBlur } }) => (
                    <CustomTextField
                      fullWidth
                      variant="outlined"
                      value={value}
                      onBlur={onBlur}
                      label="密码"
                      onChange={onChange}
                      id="auth-login-v2-password"
                      error={Boolean(errors.password)}
                      {...(errors.password && {
                        helperText: errors.password.message,
                      })}
                      type={showPassword ? "text" : "password"}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton
                              edge="end"
                              onMouseDown={(e) => e.preventDefault()}
                              onClick={() => setShowPassword(!showPassword)}
                            >
                              <Icon
                                fontSize="1.25rem"
                                icon={
                                  showPassword ? "tabler:eye" : "tabler:eye-off"
                                }
                              />
                            </IconButton>
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Box>
              <Box
                sx={{
                  mb: 1.75,
                  display: "flex",
                  flexWrap: "wrap",
                  alignItems: "center",
                  justifyContent: "space-between",
                }}
              >
                <FormControlLabel
                  label="记住我"
                  control={
                    <Checkbox
                      checked={rememberMe}
                      onChange={(e) => setRememberMe(e.target.checked)}
                    />
                  }
                />
                {/*<Typography component={LinkStyled} href='/forgot-password'>*/}
                {/*  忘记密码？*/}
                {/*</Typography>*/}
              </Box>
              <Button
                fullWidth
                type="submit"
                variant="contained"
                sx={{ mb: 4 }}
              >
                登录
              </Button>
              {/*<Box sx={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center' }}>*/}
              {/*  <Typography sx={{ color: 'text.secondary', mr: 2 }}>New on our platform?</Typography>*/}
              {/*  <Typography href='/register' component={LinkStyled}>*/}
              {/*    Create an account*/}
              {/*  </Typography>*/}
              {/*</Box>*/}
              <Divider
                sx={{
                  color: "text.disabled",
                  "& .MuiDivider-wrapper": { px: 6 },
                  fontSize: theme.typography.body2.fontSize,
                  my: (theme) => `${theme.spacing(6)} !important`,
                }}
              >
                &#169;2024 SEYSOAI. All rights reserved.
              </Divider>
            </form>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
};

LoginPage.getLayout = (page: ReactNode) => <BlankLayout>{page}</BlankLayout>;

LoginPage.guestGuard = true;

export default LoginPage;
